package cn.bocweb.spinning.view.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.DelExamrecordBean;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.LibListBean;
import cn.bocweb.spinning.model.Bean.TestRecordBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.adapter.MyTestNoteAdapter;
import cn.bocweb.spinning.view.common.BaseActivity;
import de.greenrobot.event.EventBus;

public class MyTestNoteActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.recycleview)
    RecyclerView recycleview;
    @Bind(R.id.btn_clear)
    TextView btnClear;
    @Bind(R.id.my_exam_note_refresh)
    SwipeRefreshLayout myExamNoteRefresh;

    boolean isClearAll, isLastPage = false, isSlidingToLast = false;;
    UserPresenter presenter;
    MyTestNoteAdapter adapter;
    String userid, libid;
    int page = 1;
    List<TestRecordBean.DataEntity> list;
    ItemTouchHelper.Callback callback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            presenter.delExamrecord(libid, userid, "2", list.get(viewHolder.getAdapterPosition()).getTestid());
            list.remove(viewHolder.getAdapterPosition());
            adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
        }

        @Override
        public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
            super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
                //滑动时改变Item的透明度
                final float alpha = 1 - Math.abs(dX) / (float) viewHolder.itemView.getWidth();
                viewHolder.itemView.setAlpha(alpha);
                viewHolder.itemView.setTranslationX(dX);
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_test_note);
        ButterKnife.bind(this);

        EventBus.getDefault().register(this);

        initList();
        initToolbar();
        initClickBtn();
        initModel();
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    private void initModel() {
        UserBean.DataEntity dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(this);
        userid = dataEntity.getUserid();

        LibListBean.DataEntity libList = new LibListBean.DataEntity();
        libList.readLibListIntoLocal(this);
        libid = libList.getId();

        presenter = new UserPresenterImp();
        presenter.testRecord(userid, libid, "9", "1");
        showLoading();
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    private void initList() {
        list = new ArrayList<>();

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);

        adapter = new MyTestNoteAdapter(list);
        adapter.setOnItemClickLitener(new MyTestNoteAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                Intent intent = new Intent(MyTestNoteActivity.this, TestDetailActivity.class);
                intent.putExtra(Constant.TEST_DETAIL, list.get(position).getTestid());
                startActivity(intent);
            }
        });
        recycleview.setAdapter(adapter);
        recycleview.setLayoutManager(manager);

        ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(recycleview);
        myExamNoteRefresh.setColorSchemeResources(new int[]{R.color.colorPrimary});
        myExamNoteRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                list.clear();
                isLastPage = false;
                adapter.notifyDataSetChanged();
                presenter.testRecord(userid, libid, "9", String.valueOf(page));
                myExamNoteRefresh.setRefreshing(false);
            }


        });

        recycleview.addOnScrollListener(new RecyclerView.OnScrollListener(){
            //用来标记是否正在向最后一个滑动，既是否向右滑动或向下滑动
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                LinearLayoutManager manager = (LinearLayoutManager)recyclerView.getLayoutManager();
                // 当不滚动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //获取最后一个完全显示的ItemPosition
                    int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                    int totalItemCount = manager.getItemCount();

                    // 判断是否滚动到底部，并且是向右滚动
                    if (lastVisibleItem == (totalItemCount -1) && isSlidingToLast) {
                        //加载更多功能的代码
                        if (!isLastPage) {
                            page++;
                            presenter.testRecord(userid, libid, "9", String.valueOf(page));
                        } else {
                            DeviceUtil.MyToast(MyTestNoteActivity.this, "已经是最后一页");
                        }
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
                if(dy > 0){
                    //大于0表示，正在向右滚动
                    isSlidingToLast = true;
                }else{
                    //小于等于0 表示停止或向左滚动
                    isSlidingToLast = false;
                }

            }
        });
    }

    private void initToolbar() {
        LibListBean.DataEntity dataEntity = new LibListBean.DataEntity();
        dataEntity.readLibListIntoLocal(this);
        toolbar.setTitle(dataEntity.getTitle());
        toolbar.setNavigationIcon(R.mipmap.btn_exit);
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initClickBtn() {
        btnClear.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_clear: {
                if (list.isEmpty()) {
                    DeviceUtil.MyToast(MyTestNoteActivity.this, "暂无数据");
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("提示");
                    builder.setMessage("确定删除所有记录");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (isClearAll) {
                                DeviceUtil.MyToast(MyTestNoteActivity.this, "考试数据已经全部清除");
                            } else {
                                presenter.delExamrecord(libid, userid, "1", "");
                                isClearAll = true;

                                dialog.dismiss();
                            }
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                }
                break;
            }
        }
    }

    public void onEventMainThread(TestRecordBean bean) {
        if (bean.getReturn_code() == 0) {
            list.addAll(bean.getData());
            adapter.notifyDataSetChanged();
        } else if(bean.getReturn_code() == -203) {
            DeviceUtil.MyToast(this, bean.getMsg());
            isLastPage = true;
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
        hideLoading();
    }

    public void onEventMainThread(DelExamrecordBean bean) {
        DeviceUtil.MyToast(this, bean.getMsg());
        if (bean.getReturn_code() == 0) {
            if (isClearAll) {
                list.clear();
                adapter.notifyDataSetChanged();
            }
        }
    }

    public void onEventMainThread(ErrorBean bean) {
        hideLoading();
        DeviceUtil.MyToast(this, bean.getErrorMsg());
    }
}
